package com.bw.merchant.view

import android.app.Activity
import android.app.DatePickerDialog
import android.content.Intent
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.bw.base.constants.ApiConst
import com.bw.base.constants.RoutePath
import com.bw.base.constants.UserConst
import com.bw.common.view.BaseMvvmActivity
import com.bw.image.GlideImageLoader
import com.bw.merchant.adapter.ImageAdapter
import com.bw.merchant.databinding.ActivitySettledApplyBinding
import com.bw.merchant.entity.MerchantEntity
import com.bw.merchant.net.SettledViewModel
import com.tencent.mmkv.MMKV
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import java.io.File

import java.util.*
import kotlin.random.Random


/**
 * 智慧园区-04-商家推荐V1.1
 * 入驻申请
 * 兰宏宇
 * 20250510
 */
@Route(path = RoutePath.PATH_MERCHANT_SETTLED_APPLY)
class SettledApplyActivity : BaseMvvmActivity<ActivitySettledApplyBinding, SettledViewModel>() {

    private val merchantEntity: MerchantEntity = MerchantEntity()
    private lateinit var imageAdapter: ImageAdapter
    private var uid:Int = -1
    private val imageUpLoadList:MutableList<String> = mutableListOf()

    override fun initView() {
        binding.ivBack.setOnClickListener { finish() }
        uid = MMKV.defaultMMKV().decodeInt(UserConst.USER_ID)

        imageAdapter = ImageAdapter()
        imageAdapter.data.add("初始")
        binding.rvImage.adapter = imageAdapter
        binding.rvImage.layoutManager = GridLayoutManager(this,4)

        binding.btnSubmit.setOnClickListener {

            vm.getSerialNumber()


        }

        binding.ivEntryTime.setOnClickListener {

            // 获取当前日期
            val calendar = Calendar.getInstance()
            val year = calendar.get(Calendar.YEAR)
            val month = calendar.get(Calendar.MONDAY)
            val day = calendar.get(Calendar.DAY_OF_MONTH)

            // 创建日期选择对话框
            val dataPickerDialog = DatePickerDialog(
                this,
                { _, selectedYear, selectedMonth, selectedDay ->
                    // 处理选择的日期
                    val selectedDate = "$selectedYear-${selectedMonth + 1}-$selectedDay"
                    Toast.makeText(this, "选择的日期是: $selectedDate", Toast.LENGTH_SHORT).show()
                    binding.etEntryTime.setText("$selectedDate")
                },
                year, month, day
            )
            //显示日期选择器
            dataPickerDialog.show()

        }

        binding.llOther.setOnClickListener {
            PictureSelector.create(this,103).selectPicture()
        }

        imageAdapter.setOnItemClickListener { adapter, view, position ->
            val item = imageAdapter.data[position]
            if(item=="初始"){
                PictureSelector.create(this,103).selectPicture()
            }
        }


    }


    override fun initData() {
        vm.postMerchantSuccess.observe(this){
            ToastUtils.showShort("申请成功")
            finish()
        }

        vm.uploadFileSuccess.observe(this){
            //http://10.161.9.80:2207/images/mm/437/%E5%9B%BE%E7%89%871.png
            val regex = Regex("[a-f0-9]{32}\\.\\w+")  // 匹配 32 位哈希值 + 扩展名
            val fileName = regex.find(it)?.value ?: ""
            imageUpLoadList.add("${ApiConst.BASE_URL}/images/module_merchant/${uid}/${fileName}")
        }

        vm.serialNumberSuccess.observe(this){
            merchantEntity.applicationNumber = it

            if(merchantEntity.applicationNumber==""){
                merchantEntity.applicationNumber = "RZ${Random.nextInt(1000000, 10000000)}"
            }
            merchantEntity.enterpriseName = binding.etEnterpriseName.text.toString()
            merchantEntity.contactName = binding.etContactName.text.toString()
            merchantEntity.contactMethod = binding.etContactMethod.text.toString()
            merchantEntity.entryTime = binding.etEntryTime.text.toString()
            binding.etApplicationArea.text.toString().run {
                if (this.isEmpty()) {
                    merchantEntity.applicationArea = 0.0
                } else {
                    merchantEntity.applicationArea = this.toDouble()
                }
            }
            binding.etEntryPersonnel.text.toString().run {
                if (this.isEmpty()) {
                    merchantEntity.entryPersonnel = 0
                } else {
                    merchantEntity.entryPersonnel = this.toInt()
                }
            }

            if (
                merchantEntity.enterpriseName.isEmpty() ||
                merchantEntity.contactName.isEmpty() ||
                merchantEntity.contactMethod.isEmpty() ||
                merchantEntity.entryTime.isEmpty() ||
                merchantEntity.applicationArea == 0.0 ||
                merchantEntity.entryPersonnel == 0
            ) {
                ToastUtils.showShort("请先输入内容")
                return@observe
            }

            merchantEntity.documents = imageUpLoadList

            vm.postMerchant(merchantEntity)

        }



    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==103&&resultCode== Activity.RESULT_OK){
            val pictureBean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            addImage(pictureBean.path)
        }
    }

    /**
     * 显示rv还是显示提示信息
     */
    fun showImageRV(){
        if(imageAdapter.data.size>1){
            binding.ivAdd.visibility = View.INVISIBLE
            binding.tvAdd.visibility = View.INVISIBLE
            binding.rvImage.visibility = View.VISIBLE
        }else{
            binding.ivAdd.visibility = View.VISIBLE
            binding.tvAdd.visibility = View.VISIBLE
            binding.rvImage.visibility = View.INVISIBLE
        }
    }

    /**
     * 将用户选择的图片放入适配器并显示
     */
    fun addImage(path:String){
        var index = imageAdapter.data.size - 1
        index = if(index>=0) index else 0
        imageAdapter.data.add(index,path)
        vm.uploadFile(File(path),"module_merchant",uid.toString())
        showImageRV()
        imageAdapter.notifyDataSetChanged()
    }




}